﻿Imports System.Collections.Generic
Imports System.Text
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Data
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Imaging
Imports System.Windows.Shapes
Imports System.Data
Imports System.Data.SqlClient
Imports Microsoft.Practices.EnterpriseLibrary.Data.Sql

''' <summary>
''' Interaction logic for UsersWindow.xaml
''' </summary>
Partial Public Class UsersWindow
    Inherits Window
    ' These are global object which will be use to communicate with the 
    ' database whithin this class
    Private objSqlDatabase As New SqlDatabase(GlobalClass._ConStr)
    Private objDatabaseClass As New DatabaseClass(GlobalClass._ConStr)
    Private _UserID As Int32 = -1

    Public Sub New()
        Me.Cursor = Cursors.Wait
        Me.InitializeComponent()
        If objDatabaseClass.CheckConnection() Then
            GetPermissionTypes()
            GetAllUsers()
        Else
            MessageBox.Show(ErrorMessages.[Default].NoConnection, "Error", MessageBoxButton.OK, MessageBoxImage.[Error])
            Me.DialogResult = False
        End If
        Me.Cursor = Cursors.Arrow
    End Sub

    ''' <summary>
    '''When the user close the window this event will be fired
    ''' </summary>
    Private Sub CloseCommand_Executed(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
        Me.Close()
    End Sub

    ''' <summary>
    '''This event is for moving the window
    '''</summary>
    Private Sub Window_MouseLeftButtonDown(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
        Me.DragMove()
    End Sub

    ''' <summary>
    '''This method populate the users Grid
    ''' </summary>
    Private Sub GetAllUsers()
        Dim spName As String = "Get_All_Users"
        Try
            Dim ds As DataSet = objSqlDatabase.ExecuteDataSet(CommandType.StoredProcedure, spName)
            UsersGridView.ItemsSource = ds.Tables(0).DefaultView
            UsersGridView.SelectedIndex = -1
            btnEdit.IsEnabled = True
            btnDelete.IsEnabled = True
        Catch generatedExceptionName As SqlException
        End Try
    End Sub

    ''' <summary>
    '''This method populate the permission combobox
    ''' </summary>
    Private Sub GetPermissionTypes()
        Dim commandText As String = "SELECT PermissionID,Description FROM Permissions"
        Try
            Dim ds As DataSet = objSqlDatabase.ExecuteDataSet(CommandType.Text, commandText)
            Dim permisionsList As New List(Of PersmissionClass)()
            For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                permisionsList.Add(New PersmissionClass(Convert.ToInt32(ds.Tables(0).Rows(i)("PermissionID")), ds.Tables(0).Rows(i)("Description").ToString()))
            Next
            ds = Nothing
            cmbPermission.ItemsSource = permisionsList
            cmbPermission.DisplayMemberPath = "Permission"
            cmbPermission.SelectedValuePath = "PermissionID"
            cmbPermission.SelectedIndex = -1
        Catch generatedExceptionName As SqlException
            MessageBox.Show(ErrorMessages.[Default].NoConnection, "Error", MessageBoxButton.OK, MessageBoxImage.[Error])
        End Try

    End Sub

    Private Sub btnNewUser_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        txbBorderTitle.Text = "New User"
        cmbPermission.SelectedIndex = 0
        BorderAddEdit.IsEnabled = True

        _UserID = -1
        txtFullName.Text = ""
        txtUserName.Text = ""
        pbPassword.Password = ""
        pbConfirmPassword.Password = ""
        pbPassword.IsEnabled = True
        pbConfirmPassword.IsEnabled = True
        cmbPermission.SelectedIndex = -1
        UsersGridView.IsEnabled = True
    End Sub

    Private Sub btnEdit_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        If UsersGridView.SelectedItems.Count > 0 Then
            UsersGridView.IsEnabled = False
            txbBorderTitle.Text = "Edit User"
            _UserID = Convert.ToInt32(DirectCast(UsersGridView.SelectedItem, DataRowView)("UserID"))
            txtFullName.Text = DirectCast(UsersGridView.SelectedItem, DataRowView)("FullName").ToString()
            txtUserName.Text = DirectCast(UsersGridView.SelectedItem, DataRowView)("UserName").ToString()
            Dim userType As Int16 = Convert.ToInt16(DirectCast(UsersGridView.SelectedItem, DataRowView)("PermissionID"))
            cmbPermission.SelectedValue = userType
            pbPassword.IsEnabled = False
            pbConfirmPassword.IsEnabled = False
            pbPassword.Password = "123456"
            pbConfirmPassword.Password = "123456"
            BorderAddEdit.IsEnabled = True
        Else
            MessageBox.Show(ErrorMessages.[Default].NoRowSelected, "Error", MessageBoxButton.OK, MessageBoxImage.[Error])
        End If
    End Sub

    Private Sub btnDelete_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Me.Cursor = Cursors.Wait
        If UsersGridView.SelectedItems.Count > 0 Then
            If MessageBox.Show(ErrorMessages.[Default].ConfirmDelete, "Delete", MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.Yes Then
                If objDatabaseClass.CheckConnection() Then
                    Dim spName As String = "Delete_User"
                    Dim spParams As Object() = New Object(0) {}
                    spParams(0) = Convert.ToInt32(DirectCast(UsersGridView.SelectedItem, DataRowView)("UserID"))
                    Try
                        Dim result As Integer = objSqlDatabase.ExecuteNonQuery(spName, spParams)
                        If result > 0 Then
                            GetAllUsers()
                            Reset()
                        End If
                    Catch generatedExceptionName As SqlException
                        'we check something
                        MessageBox.Show(ErrorMessages.[Default].UnhandledException, "Error", MessageBoxButton.OK, MessageBoxImage.[Error])
                    End Try
                Else
                    MessageBox.Show(ErrorMessages.[Default].NoConnection, "Error", MessageBoxButton.OK, MessageBoxImage.[Error])
                End If
            End If
        Else
            MessageBox.Show(ErrorMessages.[Default].NoRowSelected, "Error", MessageBoxButton.OK, MessageBoxImage.[Error])
        End If
        Me.Cursor = Cursors.Arrow
    End Sub

    ''' <summary>
    '''This is for reseting the selected user password to 123
    ''' </summary>
    Private Sub btnResetPassword_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Me.Cursor = Cursors.Wait
        If UsersGridView.SelectedItems.Count > 0 Then
            If MessageBox.Show(ErrorMessages.[Default].ConfirmResetPassword, "Reset Password", MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.Yes Then
                If objDatabaseClass.CheckConnection() Then
                    Dim spName As String = "Reset_User_Passw0rd"
                    Dim spParams As Object() = New Object(0) {}
                    spParams(0) = Convert.ToInt32(DirectCast(UsersGridView.SelectedItem, DataRowView)("UserID"))
                    Try
                        Dim result As Integer = objSqlDatabase.ExecuteNonQuery(spName, spParams)
                        If result > 0 Then
                            MessageBox.Show(ErrorMessages.[Default].ResetPassSucceed)
                        End If
                    Catch generatedExceptionName As SqlException
                    End Try
                Else
                    MessageBox.Show(ErrorMessages.[Default].NoConnection, "Error", MessageBoxButton.OK, MessageBoxImage.[Error])
                End If
            End If
        Else
            MessageBox.Show(ErrorMessages.[Default].NoRowSelected, "Error", MessageBoxButton.OK, MessageBoxImage.[Error])
        End If
        Me.Cursor = Cursors.Arrow
    End Sub

    Private Sub btnSave_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Me.Cursor = Cursors.Wait
        If txbBorderTitle.Text = "New User" Then
            Dim errorText As String = ""
            Dim state As Boolean = False
            If txtFullName.Text.Length < 2 Then
                errorText += ErrorMessages.[Default].UserFullNameEmpty + vbLf
                state = True
            End If
            If txtUserName.Text.Length < 1 Then
                errorText += ErrorMessages.[Default].UserNameEmpty + vbLf
                state = True
            End If
            If pbPassword.Password.Length < 3 Then
                errorText += ErrorMessages.[Default].PasswordEmpty + vbLf
                state = True
            ElseIf Not CheckPassword(pbPassword.Password, pbConfirmPassword.Password) Then
                errorText += ErrorMessages.[Default].ConflictPassword + vbLf
                state = True
            End If
            If Not (cmbPermission.SelectedIndex > -1) Then
                errorText += ErrorMessages.[Default].PermissionNotChoosed
                state = True
            End If
            If state = False Then
                If objDatabaseClass.CheckConnection() Then
                    Dim spName As String = "Create_User"
                    Dim spParams As Object() = New Object(3) {}
                    spParams(0) = txtFullName.Text
                    spParams(1) = txtUserName.Text
                    spParams(2) = GlobalClass.GetMd5Hash(pbPassword.Password)
                    spParams(3) = Convert.ToInt16(cmbPermission.SelectedValue)
                    Try
                        Dim result As Integer = objSqlDatabase.ExecuteNonQuery(spName, spParams)
                        If result > 0 Then
                            Reset()
                            GetAllUsers()
                            MessageBox.Show(String.Format(ErrorMessages.[Default].RecordCreatedSuccessfully, "User"))
                        End If
                    Catch ex As SqlException
                        If ex.Number = 2627 Then
                            MessageBox.Show(String.Format(ErrorMessages.[Default].RepeatedRecord, "User Name"), "Error", MessageBoxButton.OK, MessageBoxImage.[Error])
                        End If
                    End Try
                Else
                    MessageBox.Show(ErrorMessages.[Default].NoConnection, "Error", MessageBoxButton.OK, MessageBoxImage.[Error])
                End If
            Else
                MessageBox.Show(errorText, "Error", MessageBoxButton.OK, MessageBoxImage.[Error])
            End If
        ElseIf txbBorderTitle.Text = "Edit User" Then
            Dim errorText As String = ""
            Dim state As Boolean = False
            If txtFullName.Text.Length < 2 Then
                errorText += ErrorMessages.[Default].UserFullNameEmpty + vbLf
                state = True
            End If
            If txtUserName.Text.Length < 1 Then
                errorText += ErrorMessages.[Default].UserNameEmpty + vbLf
                state = True
            End If
            If Not (cmbPermission.SelectedIndex > -1) Then
                errorText += ErrorMessages.[Default].PermissionNotChoosed
                state = True
            End If
            If state = False Then
                If objDatabaseClass.CheckConnection() Then
                    If _UserID <> -1 Then
                        Dim spName As String = "Update_User"
                        Dim spParams As Object() = New Object(3) {}
                        spParams(0) = _UserID
                        spParams(1) = txtFullName.Text
                        spParams(2) = txtUserName.Text
                        spParams(3) = Convert.ToInt16(cmbPermission.SelectedValue)
                        Try
                            Dim result As Integer = objSqlDatabase.ExecuteNonQuery(spName, spParams)
                            If result > 0 Then
                                Reset()
                                GetAllUsers()
                                MessageBox.Show(ErrorMessages.[Default].EditedSuccessfully)
                            End If
                        Catch ex As SqlException
                            If ex.Number = 2627 Then
                                MessageBox.Show(String.Format(ErrorMessages.[Default].RepeatedRecord, "User Name"), "Error", MessageBoxButton.OK, MessageBoxImage.[Error])

                            End If
                        End Try
                    Else
                        MessageBox.Show(ErrorMessages.[Default].UnhandledException, "Error", MessageBoxButton.OK, MessageBoxImage.[Error])
                    End If
                Else
                    MessageBox.Show(ErrorMessages.[Default].NoConnection, "Error", MessageBoxButton.OK, MessageBoxImage.[Error])
                End If
            Else
                MessageBox.Show(errorText, "Error", MessageBoxButton.OK, MessageBoxImage.[Error])
            End If
        End If
        Me.Cursor = Cursors.Arrow
    End Sub

    ''' <summary>
    '''Compares Password with Confirm password
    '''returns True when both are the same
    '''returns false when they are not the same
    ''' </summary>
    Private Function CheckPassword(ByVal pass1 As String, ByVal pass2 As String) As Boolean
        If pass1 = pass2 Then
            Return (True)
        Else
            Return (False)
        End If
    End Function

    Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Reset()
    End Sub

    ''' <summary>
    '''Reset the textboxes and other controls after save or cancel functions
    ''' </summary>
    Private Sub Reset()
        txbBorderTitle.Text = ""
        _UserID = -1
        txtFullName.Text = ""
        txtUserName.Text = ""
        pbPassword.Password = ""
        pbConfirmPassword.Password = ""
        cmbPermission.SelectedIndex = -1
        BorderAddEdit.IsEnabled = False
        UsersGridView.IsEnabled = True
    End Sub
End Class

Class PersmissionClass
    Public Sub New(ByVal permisionID As Integer, ByVal permission As String)
        Me._permissionID = permisionID
        Me._permission = permission
    End Sub

    Private _permissionID As Integer = -1
    Public Property PermissionID() As Integer
        Get
            Return _permissionID
        End Get
        Set(ByVal value As Integer)
            _permissionID = value
        End Set
    End Property

    Private _permission As String = ""
    Public Property Permission() As String
        Get
            Return _permission
        End Get
        Set(ByVal value As String)
            _permission = value
        End Set
    End Property
End Class
